<script setup lang="ts">
import { ref, onBeforeUnmount } from 'vue'
import QRCode from 'qrcode'
import { apiQrcodeGenerate, apiQrcodePoll } from '@renderer/api/bilibili'
import logo from '@renderer/assets/bilibili.svg'
import { storageLocal } from '@renderer/tools/index'
import { useRouter, useRoute } from 'vue-router'
import { useUserStore } from '@renderer/stores/user'
import chalk from 'chalk'

const router = useRouter()
const route = useRoute()
const qrImage = ref('')
const blueBold = chalk.blueBright.bold
let timer: NodeJS.Timeout | null = null

onBeforeUnmount(() => {
  if (timer) {
    clearTimeout(timer)
  }
})

getQR()

async function getQR() {
  const response = await apiQrcodeGenerate()
  const {
    data: { url, qrcode_key }
  } = response

  const rootStyle = getComputedStyle(document.documentElement)
  const colorPrimary = rootStyle.getPropertyValue('--color-primary')

  qrImage.value = await QRCode.toDataURL(url, {
    width: 192,
    margin: 0,
    color: {
      dark: colorPrimary, // 二维码颜色
      light: '#0000' // 背景颜色，#0000 表示透明
    }
  })

  timer = setTimeout(() => pollQR(qrcode_key), 1500)
}

async function pollQR(qrcode_key: number) {
  const response = await apiQrcodePoll({ qrcode_key })
  console.log(blueBold('登录===>'), response.data)
  const {
    data: { code, refresh_token }
  } = response

  if (code === 0) {
    storageLocal().setItem('refresh_token', refresh_token)

    router.push({ name: 'loyout' })

    useUserStore().getUserInfo()
  } else if (code === 86038) {
    getQR()
  } else if (route.name === 'login') {
    timer = setTimeout(() => pollQR(qrcode_key), 1500)
  }
}
</script>

<template>
  <div class="login">
    <img :src="logo" class="logo" loading="lazy" />
    <div v-if="qrImage" class="qr-code-container">
      <img :src="qrImage" loading="lazy" />
    </div>
    <div class="qr-code-info">打开哔哩哔哩APP扫码登录</div>
  </div>
</template>

<style lang="less">
.login {
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding-bottom: 12vh;
  .logo {
    margin: 32px;
  }
  .qr-code-container {
    background-color: var(--color-primary-bg);
    padding: 24px;
    padding-bottom: 20px;
    border-radius: 1.25rem;
    margin-bottom: 12px;
  }
  .qr-code-info {
    color: var(--color-text);
    text-align: center;
    margin-bottom: 28px;
  }
}
</style>
